<template>
  <div style="display:flex;flex-direction: row">
    <admin_left/>
    <div class="main-container">
      <div id="main" style="width: 700px;height:400px;"></div>
      <div id="main2" style="width: 700px;height:400px;"></div>
    </div>
  </div>
</template>
<script>
import user_left from "@/components/admin_left.vue";
import {Notification} from "element-ui";
import {
  getAllToupiaoPost,
  getPostComment,
  favorPost,
  viewPost,
  addComment,
  responseComment,
  uploadToupiaoImage,
  toupiao,
  deletePost,
  uploadPostToupiaoContent
} from "@/api/user_api";
import axios from "axios";
import * as echarts from "echarts";
import admin_left from "@/components/admin_left.vue";
import filterPosts from "core-js/internals/array-iteration";




export default {
  components: {
    admin_left,
  },
  data() {
    return {
      user: {
        userId: parseInt(localStorage.getItem("id"))
      },
      posts: [],
      filterPosts: [],
      sortType: "按时间",
      filterType: "全部",
      drawerVisible: false,
      drawerPost: {},
      comment: {},
      postComments: [],
      sonComments: [],
      isLoadingComments: false,
      visible: {
        addVisible: false,
        addCommentVisible: false,
        sonCommentVisible: false
      },
      dormitoryNameArray:[],
      countArray:[],
      dormitoryNameArray2:[],
      countArray2:[],
      newPost: {
        content: "",
        dormitoryName:"",
        userName:"",
        fileList: []
      },
      newComment: {
        content: ""
      },
      newSonCommentContent: "",
      uploadLoading: false
    }
  },
  created() {

  },
  mounted() {
    this.getAllToupiaoPost();

  },
  methods: {
    tojitong(){
      var myChart = echarts.init(document.getElementById('main'));
// 绘制图表
      myChart.setOption({
        title: {
          text: '投票统计'
        },
        tooltip: {},
        xAxis: {
          data: this.dormitoryNameArray
        },
        yAxis: {},
        series: [
          {
            name: '票数',
            type: 'bar',
            data: this.countArray
          }
        ]
      });
    },
    tojitong2(){
      var myChart = echarts.init(document.getElementById('main2'));
// 绘制图表
      myChart.setOption({
        title: {
          text: '投票排名'
        },
        tooltip: {},
        xAxis: {
          data: this.dormitoryNameArray2
        },
        yAxis: {},
        series: [
          {
            name: '票数',
            type: 'line',
            data: this.countArray2
          }
        ]
      });
    },
    getAllToupiaoPost() {
      const param = {
        userId: this.user.userId
      }
      getAllToupiaoPost(param).then(response => {
        if (response.data.code === "SUCCESS") {
          this.posts = response.data.data;
          this.filterPosts = response.data.data;
          this.filterPosts.forEach(item => {
            this.dormitoryNameArray.push(item.dormitoryName);
            this.countArray.push(item.count);
          });
          this.tojitong();
          this.posts.sort((a, b) =>  b.count -a.count );
          this.posts.forEach(item => {
            this.dormitoryNameArray2.push(item.dormitoryName);
            this.countArray2.push(item.count);
          });
          this.tojitong2();
        } else if (response.data.code === "ERROR") {
          Notification({
            title: "获取信息失败",
            type: "error"
          });
        } else if (response.data.code === "TIMEOUT") {
          Notification({
            title: "登录信息已过期，请重新登录",
            type: "warning"
          });
        }
      });
    },
    getComments() {
      this.isLoadingComments = true;
      const param = {
        postId: this.drawerPost.id,
        userId: this.user.userId
      }
      getPostComment(param).then(response => {
        if (response.data.code === "SUCCESS") {
          this.drawerPost.comments = response.data.data;
        } else if (response.data.code === "ERROR") {
          Notification({
            title: "获取评论信息失败",
            type: "error"
          });
        } else if (response.data.code === "TIMEOUT") {
          Notification({
            title: "登录信息已过期，请重新登录",
            type: "warning"
          });
        }
        return null;
      }).finally(() => {
        this.isLoadingComments = false;
      });
    },
    openPost(post) {
      const param = {
        id: post.id,
        userId: this.user.userId
      }
      toupiao(param).then(response => {
        if (response.data.code === "SUCCESS") {
          post.count += 1;
        } else if (response.data.code === "ERROR") {
          Notification({
            title: "一个人只能对一个宿舍投票一次",
            type: "error"
          });
        } else if (response.data.code === "TIMEOUT") {
          Notification({
            title: "登录信息已过期，请重新登录",
            type: "warning"
          });
        }
      });
    },
    openSonComments(comment) {
      this.comment = comment;
      this.sonComments = comment.sonComment;
      this.visible.sonCommentVisible = true;
    },
    userFavor() {
      const param = {
        postId: this.drawerPost.id,
        userId: this.user.userId
      }
      favorPost(param).then(response => {
        if (response.data.code === "SUCCESS") {
          if (this.drawerPost.isFavor === "是") {
            this.drawerPost.isFavor = "否";
            this.drawerPost.favorCount -= 1;
          } else {
            this.drawerPost.isFavor = "是";
            this.drawerPost.favorCount += 1;
          }
          Notification({
            title: "操作成功",
            message: response.data.data,
            type: "success"
          });
        } else if (response.data.code === "TIMEOUT") {
          Notification({
            title: "登录信息已过期，请重新登录",
            type: "warning"
          });
        }
      });
    },
    addComment() {
      const param = {
        postId: this.drawerPost.id,
        userId: this.user.userId,
        content: this.newComment.content
      }
      addComment(param).then(response => {
        if (response.data.code === "SUCCESS") {
          this.newComment.content = "";
          this.getComments();
          this.drawerPost.commentCount += 1;
          this.visible.addCommentVisible = false;
          Notification({
            title: "评论成功",
            type: "success"
          });
        } else if (response.data.code === "ERROR") {
          Notification({
            title: "评论失败",
            type: "error"
          });
        } else if (response.data.code === "TIMEOUT") {
          Notification({
            title: "登录信息已过期，请重新登录",
            type: "warning"
          });
        }
      });
    },
    responseComment() {
      const param = {
        postId: this.drawerPost.id,
        userId: this.user.userId,
        responsePostId: this.comment.id,
        content: this.newSonCommentContent
      }
      responseComment(param).then(response => {
        if (response.data.code === "SUCCESS") {
          this.newSonCommentContent = "";
          this.getComments();
          this.visible.sonCommentVisible = false;
          Notification({
            title: "回复成功",
            type: "success"
          });
        } else if (response.data.code === "ERROR") {
          Notification({
            title: "回复失败",
            type: "error"
          });
        } else if (response.data.code === "TIMEOUT") {
          Notification({
            title: "登录信息已过期，请重新登录",
            type: "warning"
          });
        }
      });
    },
    // 图片上传需要的方法
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isGIF = file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 1;

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF 格式!');
      }
      if (!isLt1M) {
        this.$message.error('上传头像图片大小不能超过 1MB!');
      }
      return (isJPG || isPNG || isGIF) && isLt1M;
    },
    uploadPost(){
      const file = this.$refs.upload.uploadFiles[0];

        // 获取要上传的图片

        const formData = new FormData();
        formData.append('file', file.raw);
        this.uploadLoading = true; // 显示遮罩层
        // 获取文本
        const ContentParam = {
          userId: this.user.userId,
          userName: this.newPost.userName,
          dormitoryName: this.newPost.dormitoryName,
          content: this.newPost.content
        }

      // 判断文本是否为空且图片是否满足要求
      if (this.newPost.content === "") {
        this.uploadLoading = false; // 隐藏遮罩层
        Notification({
          title: "请填写完整信息",
          type: "warning"
        });
        return;
      }
      // 先上传文本，待获得响应的data.data后将其放到axios的请求头头"postId"中上传图片
      uploadPostToupiaoContent(ContentParam).then(response => {
        if (response.data.code === "SUCCESS") {
          const postId = response.data.data;
          axios.defaults.headers.post['postId'] = postId;
          uploadToupiaoImage(formData).then(response => {
            if (response.data.code === "SUCCESS") {
              this.uploadLoading = false; // 隐藏遮罩层
              this.visible.addVisible = false;
              this.getAllPost();
              Notification({
                title: "上传成功",
                type: "success"
              });
            } else if (response.data.code === "ERROR") {
              this.uploadLoading = false; // 隐藏遮罩层
              this.visible.addVisible = false;
              Notification({
                title: "上传失败",
                type: "error"
              });
            } else if (response.data.code === "TIMEOUT") {
              this.uploadLoading = false; // 隐藏遮罩层
              this.visible.addVisible = false;
              Notification({
                title: "登录信息已过期，请重新登录",
                type: "warning"
              });
            }
          });
        }
      });
    },
    // 删除帖子
    deletePost(id) {
      this.$confirm('此操作将永久删除该帖子, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = {
          postId: parseInt(id)
        }
        deletePost(param).then(response => {
          if (response.data.code === "SUCCESS") {
            this.posts = this.posts.filter(post => post.id !== id);
            this.filterPosts = this.filterPosts.filter(post => post.id !== id);
            this.drawerVisible = false;
            Notification({
              title: "删除成功",
              type: "success"
            });
          } else if (response.data.code === "ERROR") {
            Notification({
              title: "删除失败",
              type: "error"
            });
          } else if (response.data.code === "TIMEOUT") {
            Notification({
              title: "登录信息已过期，请重新登录",
              type: "warning"
            });
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },


  },

}
</script>
<style scoped>
.main-container {
  width: 70%;
  margin: 0 auto;
}

.post {
  width: 90%;
  height: 200px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 40px;
  border: 1px solid #ccc;
  border-radius: 15px;
  box-shadow: 0 0 10px #ccc;
  transition: all 0.7s;
}

.post:hover {
  transform: scale(1.1);
  box-shadow: 0 0 20px #ccc;
  border: 1px solid #000;
  box-shadow: 0 0 10px #ccc, 10px 10px 10px #ccc;
}

.post-img {
  width: 200px;
  height: 200px;
  border-radius: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.post-img-img {
  width: 200px;
  height: 200px;
  border-radius: 15px;
  object-fit: cover;
}

.post-content {
  width: 60%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.post-user-info {
  font-weight: bold;
  font-size: 15px;
  width: 20%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.user-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  margin-top: 10px;
}

.post-info {
  width: 50%;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.el-tag {
  font-size: 25px;
}

.drawer-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.drawer-content p {
  font-size: 30px;
  margin-top: 40px;
  margin-bottom: 40px;
}

.drawer-img {
  width: 300px;
  height: 300px;
  object-fit: cover;
  border-radius: 15px;
}

.drawer-post-info {
  display: flex;
  justify-content: space-around;
  width: 50%;
  margin-top: 20px;
  align-items: center;
}

.drawer-comment {
  width: 100%;
  margin-top: 20px;
}

.favor {
  transition: all 0.5s;
}

.favor:hover {
  transform: scale(1.2);
}

.post-comment {
  width: 80%;
  height: 100px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 40px;
  margin-left: 10%;
  border: 1px solid #ccc;
  border-radius: 15px;
  box-shadow: 0 0 10px #ccc;
  transition: all 0.7s;
}

.post-comment:hover {
  transform: scale(1.1);
  box-shadow: 0 0 20px #ccc;
  border: 1px solid #000;
  box-shadow: 0 0 10px #ccc, 10px 10px 10px #ccc;
}

.post-comment-ava {
  height: 100px;
  width: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.post-comment-name {
  width: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.post-comment-name el-tag {
  font-size: 10px;
}

.post-comment-content {
  width: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.post-comment-content p {
  font-size: 15px;
}

.post-comment-time {
  width: 90px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.post-comment-time p {
  font-size: 15px;
}

.user-favor {
  transition: all 0.5s;
}

.user-favor:hover {
  transform: scale(1.3);
}

.post-comment-commentCount {
  transition: all 0.5s;
}

.post-comment-commentCount:hover {
  transform: scale(1.3);
}
</style>